//
// Created by LiuYou on 2021/8/12.
//

#include <cstdio>
#include <cstring>
#include <sys/socket.h>
#include <cassert>
#include <netinet/in.h>
#include <cstdlib>
#include <arpa/inet.h>
#include <unistd.h>


static int getBufferSize() {
    static const int BUF_SIZE = 1024;
    return BUF_SIZE;
}


/**
 * 接受带外数据
 */
int main(int argc, char** argv) {
    if (argc < 3) {
        fprintf( stderr, "用法: %s ip port\n", basename( argv[0] ));
        return 1;
    }

    char* ip = argv[1];
    char* port = argv[2];

    int socketFd = socket( PF_INET, SOCK_STREAM, 0 );
    assert( socketFd >= 0 );

    sockaddr_in localAddress = {
            .sin_family=AF_INET,
            .sin_port=htons( atoi( port ))
    };
    inet_pton( AF_INET, ip, &localAddress.sin_addr );

    int ret = bind( socketFd, (sockaddr*) &localAddress, sizeof( localAddress ));
    assert( ret != -1 );

    ret = listen( socketFd, 5 );
    assert( ret != -1 );

//    sleep( 20 );

    sockaddr_in remoteAddress;
    socklen_t socklen = sizeof( remoteAddress );
    int connectFd = accept( socketFd, (sockaddr*) &remoteAddress, &socklen );
    if (connectFd < 0) {
        perror( "accept()" );
        close( socketFd );
        exit( 1 );
    }

    char buffer[getBufferSize()];
    memset( buffer, '\0', getBufferSize());
    ssize_t returnByte = recv( connectFd, buffer, getBufferSize() - 1, 0 );
    fprintf( stdout, "得到了%zd字节从正常数据: %s\n", returnByte, buffer );

    memset( buffer, '\0', getBufferSize());
    returnByte = recv( connectFd, buffer, getBufferSize() - 1, MSG_OOB );
    fprintf( stdout, "得到了%zd字节从oob data: %s\n", returnByte, buffer );

    memset( buffer, '\0', getBufferSize());
    returnByte = recv( connectFd, buffer, getBufferSize() - 1, 0 );
    fprintf( stdout, "得到了%zd字节从正常数据: %s\n", returnByte, buffer );


    close( connectFd );
    close( socketFd );
    return 0;
}































